/*
 * @Date: 2025-07-21 23:32:59
 * @LastEditors: 贾二小 erxiao.jia@outlook.com
 * @LastEditTime: 2025-09-28 00:42:52
 * @FilePath: /admin-vue/src/stores/useRouteStore.ts
 */
import useAuth from '@/composables/system/useAuth'
import { RouteEnum } from '@/enums/RouteEnum'
import type { MenuOption } from 'naive-ui'
import { defineStore } from 'pinia'
import { RouterLink, useRoute, useRouter, type RouteLocationNormalizedLoaded } from 'vue-router'

export const useRouteStore = defineStore('useRouteStore', () => {
  /** Home route key */
  const routeHome = ref(RouteEnum.HOME)

  const menus = ref<MenuOption[]>([])
  const res_menus = ref<MenuModel[]>([])

  /**
   * 将原始菜单数据转换为NaiveUI的MenuOption[]类型
   * @param originalMenus 原始菜单数据数组
   * @returns 转换后的MenuOption数组
   */
  function convertToMenuOptions(originalMenus: Array<any>): MenuOption[] {
    const { SvgIconVNode } = useSvgIcon()
    // 递归处理菜单数据
    const processMenu = (menu: any): MenuOption => {
      const menuOption: MenuOption = {
        key: menu.router_name ?? menu.id.toString(),
        label: menu.router_name
          ? () =>
              h(
                RouterLink,
                {
                  to: {
                    name: menu.router_name,
                  },
                },
                { default: () => menu.label },
              )
          : menu.label,
        icon: menu.icon ? SvgIconVNode({ icon: menu.icon }) : undefined,
        // 处理子菜单（如果存在）
        children: menu.children ? menu.children.map((child: any) => processMenu(child)) : undefined,
      }

      /**
       *
       *
       */

      return menuOption
    }

    // 过滤掉状态不为1的菜单，并处理所有顶级菜单
    return originalMenus.filter((menu) => menu.status === 1).map((menu) => processMenu(menu))
  }

  const getGlobalMenus = async () => {
    const { loadMenus } = useAuth()
    const { data } = await loadMenus()
    res_menus.value = data
    menus.value = convertToMenuOptions(data)
  }

  const route = useRoute()
  const router = useRouter()

  const selectedKey = computed(() => {
    const name = route.name as string

    return name
  })

  /**
   * Transform menu to breadcrumb
   *
   * @param menu
   */
  function transformMenuToBreadcrumb(menu: MenuModel): BreadcrumbModel {
    const { SvgIconVNode } = useSvgIcon()
    const { children, id, label, router_name, icon } = menu

    const breadcrumb = {
      key: router_name ?? 'bc_' + id,
      label: label,
      routerName: router_name,
      /** The menu icon */
      icon: SvgIconVNode({ icon: icon }),
    } as BreadcrumbModel

    if (children?.length) {
      breadcrumb.options = children.map(transformMenuToBreadcrumb)
    }

    return breadcrumb
  }

  function getBreadcrumbsByRoute(
    route: RouteLocationNormalizedLoaded,
    menus: MenuModel[],
  ): BreadcrumbModel[] {
    const router_name = route.name as string

    for (const menu of menus) {
      if (menu.router_name === router_name) {
        return [transformMenuToBreadcrumb(menu)]
      }

      if (menu.children?.length) {
        const result = getBreadcrumbsByRoute(route, menu.children)
        if (result.length > 0) {
          return [transformMenuToBreadcrumb(menu), ...result]
        }
      }
    }

    return []
  }

  /** Global breadcrumbs */
  const breadcrumbs = computed(() =>
    getBreadcrumbsByRoute(router.currentRoute.value, res_menus.value),
  )

  return {
    routeHome,
    menus,
    getGlobalMenus,
    // searchMenus,
    selectedKey,
    breadcrumbs,
  }
})
